<template>
  <el-select v-model="selectedUsers2" multiple filterable
             @visible-change="loadSpaceMembers" :loading="isLoading">
    <el-option v-for="user in users" :key="user.id" class="select-option"
               :value="user.id" :label="user.nickname">
      <el-avatar :size="32" :src="user.avatar"/>
      <span class="m-l-10">{{ user.nickname }}</span>
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: 'UserSelect', // 用户选择，输出id [1,2,3]
  props: {
    selectedUsers: { // 已选择的用户
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      selectedUsers2: [],
      users: [],
      isLoading: false, // 正在加载列表
    };
  },
  methods: {
    // 加载用户列表
    loadSpaceMembers() {
      if (this.users.length) return; // 请求过就不再加载了
      this.isLoading = true;
      this.$api.spaceMembers.index({ spaceId: this.$route.params.spaceId })
        .then((res) => { this.users = res.data.map(item => item.user); })
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
  },
  watch: {
    selectedUsers2() { this.$emit('update:selectedUsers', this.selectedUsers2); },
  },
};
</script>

<style lang="scss">
.select-option {
  display: flex;
  align-items: center;
  padding: .5rem 1rem;
  height: auto;
}
</style>
